package cn.strive.eams.dictoption.service.impl;

import cn.strive.eams.base.exception.ServiceException;
import cn.strive.eams.base.response.StatusCode;
import cn.strive.eams.dict.mapper.DictMapper;
import cn.strive.eams.dict.pojo.dto.DictQuery;
import cn.strive.eams.dict.pojo.vo.DictVO;
import cn.strive.eams.dictoption.mapper.DictOptionMapper;
import cn.strive.eams.dictoption.pojo.dto.DictOptionQuery;
import cn.strive.eams.dictoption.pojo.dto.DictOptionSaveParam;
import cn.strive.eams.dictoption.pojo.entity.DictOption;
import cn.strive.eams.dictoption.pojo.vo.DictOptionVO;
import cn.strive.eams.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;

    @Override
    public List<DictOptionVO> selectAll(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项,参数:{}", dictOptionQuery);
        return dictOptionMapper.selectAll(dictOptionQuery);
    }

    @Override
    public void save(DictOptionSaveParam dictOptionSaveParam) {
        log.debug("保存字典项,参数:{}", dictOptionSaveParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam, dictOption);
        if (dictOption.getId() == null) {
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        } else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("删除字典项,参数:{}", id);
        dictOptionMapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典code查询字典项,参数:{}", code);
        //需要先根据字典编码,查询字典是否存在,若存在,再查询该字典下的字典项
        DictQuery dictQuery = new DictQuery();//封装字典查询对象
        dictQuery.setCode(code);//给字典查询对象设置字典编码
        List<DictVO> dictVOList = dictMapper.selectByNameAndCode(dictQuery);
        if (dictVOList.size() > 0 && dictVOList!=null) {
            DictVO dictVO = dictVOList.get(0);
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> dictOptionVOList =
                    dictOptionMapper.selectAll(dictOptionQuery);
            return dictOptionVOList;
        } else {
            throw new ServiceException(StatusCode.DATA_UN_EXISTS);
        }
    }
}
